// map.js
// Mon 15 Mar 2010 10:23:00 AM EET

/* 
Initialization and simple manipulation functions for GeoTree demo.

Copyright (c) 2010 Artem Dudarev
License: Apache 2.0
*/

var map;
var points_data = [];
var markersArray = [];

// Deletes all markers in the array by removing references to them
// http://code.google.com/apis/maps/documentation/v3/overlays.html
function deleteOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}

// Initialization function
function initialize_map() {
    var myOptions = {
        zoom: 4,
        center: new google.maps.LatLng(48.03,20),
        mapTypeControl: true,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
        navigationControl: true,
        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    // Insert this overlay map type as the first overlay map type at
    // position 0. Note that all overlay map types appear on top of
    // their parent base map.
    map.overlayMapTypes.insertAt(
        0, new CoordMapType(new google.maps.Size(256, 256)));

    google.maps.event.addListener(map, 'zoom_changed', function() {
        setTimeout(load_points, 200);
    });

    load_points();
}

// Load JSON of all points in tiles (3x3 tiles around center tile)
function load_points(){
    deleteOverlays();

    z = map.getZoom();
    centerTile = PointToTile(map.getCenter(),z);
    center =  centerTile.x + ',' + centerTile.y + ',' + z;
    
    url = '/t/?c=' + center;
    $.ajax({ url: url, success: function(data){
            points_data = eval(data);
            for(var i=0; i<points_data.length; i++){
                var lat = points_data[i]['coord'][0];
                var lon = points_data[i]['coord'][1];
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(lat,lon), 
                    map: map,
                    info: lat
                });   
                markersArray.push(marker);
                attachInfoDiv(marker,i);
                $('#marker_info').html('');
            }
      }});
}

// Update city info div when mouseover over marker
function attachInfoDiv(marker,i){
    google.maps.event.addListener(marker, "mouseover", function(e) {
            var html = '<h2>'+points_data[i]['name']+'</h2>';
            html += 'population: '+points_data[i]['importance']+'<br/>';
            var lat = points_data[i]['coord'][0];
            var lon = points_data[i]['coord'][1];
            var z = map.getZoom();
            var tile = PointToTile(new google.maps.LatLng(lat,lon),z);
            var tile_str =  tile.x + ',' + tile.y + ',' + z;
            html += 'tile: ' + tile_str;
            $('#marker_info').html(html);
        });
}
